package com.medical.client.controller.utils;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;

/**
 * @ClassName: HttpUtils
 * @Description: TODO
 * @Author: JackyLee
 * @Date: 2024/6/16 22:47
 **/
public class HttpUtils {
    public static String sendGetRequest(String url){
        try {
            HttpClient client = HttpClient.newHttpClient();
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .build();

            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            return response.body();
        }catch (Exception e){
            return null;
        }
    }

    /**
     * @Author JackyLee
     * @Description 发送POST请求并携带JSON格式的请求体
     * @Date 0:06 2024/6/17
     * @Param [url, jsonBody]
     **/
    public static String sendPostRequest(String url, String jsonBody) {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request;

        // 创建POST请求
        request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonBody))
                .build();

        try {
            // 发送请求并获取响应
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

            return response.body();
        }catch (Exception e){
            e.printStackTrace();
            return e.getMessage();
        }
    }

    public static void main(String[] args) {
        String result= """
                {"code":0,"msg":"成功","data":[{"blUpload1":"0","address":"","scale":0,"unitname":"广东华夏结构工程有限公司","jgId":null,"tradetypecode":null,"opdatetime":1513699200000,"ecotypecode":null,"districtcode":null,"relator":"","staffs":0,"dworkers":0,"relaphone":"","unitno":"zzzzzzzzzzzzzzzz1111","postcode":"","reladepname":"","chiefphone":"","chiefname":"","workers":null,"dworkerwomen":null,"uploadmemo1":"jgId为空","uploadmemo2":"","districtname":null}]}
                """;

        JsonObject jsonResult = JsonParser.parseString(result).getAsJsonObject();
        JsonArray jsonArray = jsonResult.getAsJsonArray("data");
        System.out.println(jsonArray);
    }
}
